//
//  ZineMassgeView.m
//  YZZX
//
//  Created by Easaa on 15/5/12.
//  Copyright (c) 2015年 Easaa. All rights reserved.
//

#import "ZineMassgeView.h"

@interface ZineMassgeView ()<HXHttpRequestDelegate,UIWebViewDelegate,UIScrollViewDelegate,UIGestureRecognizerDelegate>
{
    HXHttpRequest   *_httpRequest;
    UIView          *bgheadview;    //标题view
    UIView          *TabbarView;    //下边的工具栏
    UIWebView       * MassgeWebView;
    UIScrollView    *_bgscrollView;
    
    float   _textFontSize;


}

@end

@implementation ZineMassgeView

-(id)initWithEstablish:(ZilneListDataModel *)catemodel
{

    self = [super init];
    if(self)
    {
        self.DataMassgeModel = catemodel;
        self.title = @"详情";
        
        
    }
    
    return self;



}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.RefreshBut = [UIButton buttonWithType:UIButtonTypeCustom];
    self.RefreshBut.frame = CGRectMake(Dev_ScreenWidth-32, 64-32, 32, 32);
    [self.RefreshBut setImage:[UIImage imageNamed:@"action_refresh"] forState:UIControlStateNormal];
    [self.RefreshBut setImage:[UIImage imageNamed:@"action_refresh"] forState:UIControlStateHighlighted];
    // self.RefreshBut.hidden =YES;
    
    [self.RefreshBut addTarget:self action:@selector(ButMenuBseletor) forControlEvents:UIControlEventTouchUpInside];
    
    
    UIBarButtonItem *negativeSpacerRight = [[UIBarButtonItem alloc]
                                            
                                            initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                            
                                            target:nil action:nil];
    
    /**
     
     *  width为负数时，相当于btn向右移动width数值个像素，由于按钮本身和边界间距为5pix，所以width设为-5时，间距正好调整
     
     *  为0；width为正数时，正好相反，相当于往左移动width数值个像素
     
     */
    
    negativeSpacerRight.width = -12;
    
    UIBarButtonItem *rightBarBtItem = [[UIBarButtonItem alloc] initWithCustomView:self.RefreshBut];
    
    self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:negativeSpacerRight, rightBarBtItem, nil];
    
    
    
    
    
    if([YZFMDB getAllPeople:self.DataMassgeModel.id_massge]!=nil)
    {
        NSMutableArray  *arrydatasFmdb = [YZFMDB getAllPeople:self.DataMassgeModel.id_massge];
        NSMutableDictionary  *  dic = [arrydatasFmdb objectAtIndex:0];
        
        self.Content                    = [dic objectForKey:@"Content"];
        self.Image                      = [dic objectForKey:@"Title"];
        self.id_massge                  = [dic objectForKey:@"id"];
        self.ReleaseDate                = [dic objectForKey:@"ReleaseDate"];
        
        
        
        [_bgscrollView removeFromSuperview];
        [self creatViewAndContorller];
       
        
    }else if ([YZFMDB getAllPeople:self.DataMassgeModel.id_massge]==nil)
    {
        
        NSMutableArray *arrykey = [[NSMutableArray alloc]init];
        [arrykey addObject:self.DataMassgeModel.id_massge];
        
        
        
        //列表请求
        NSDictionary* dicParams = [NSDictionary dictionaryWithObjectsAndKeys:
                                   [XSZ_UICommon useridChangUaerdfLoginBoolString],    @"user_id",
                                   @"1",    @"site_id",
                                   arrykey, @"ids"
                                   ,nil];
        
        
        if (_httpRequest == nil)
        {
            _httpRequest = [[HXHttpRequest alloc] init];
            _httpRequest.delegate = self;
            
            
            
        }
        [_httpRequest requestForParams:dicParams andMethod:YZ_ZINE_ARTICIE_QUERY andTag:1001];//@"system.time"];//@"category.list"];
        


    
    }
    
    
    
}

//刷新
-(void)ButMenuBseletor
{
    
    
    NSMutableArray *arrykey = [[NSMutableArray alloc]init];
    [arrykey addObject:self.DataMassgeModel.id_massge];
    
    //列表请求
    NSDictionary* dicParams = [NSDictionary dictionaryWithObjectsAndKeys:
                               [XSZ_UICommon useridChangUaerdfLoginBoolString],    @"user_id",
                               @"1",    @"site_id",
                               arrykey, @"ids"
                               ,nil];
    
    
    if (_httpRequest == nil)
    {
        _httpRequest = [[HXHttpRequest alloc] init];
        _httpRequest.delegate = self;
        
        
        
    }
    [_httpRequest requestForParams:dicParams andMethod:YZ_ZINE_ARTICIE_QUERY andTag:1001];//@"system.time"];//@"category.list"];
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    
    
    
}

#pragma mark - HXHttpRequestDelegate  代理

- (void)requestFinished:(NSString *)responseString andStatusCode:(int)statusCode andTag:(NSInteger)tag
{
    
    
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    
    //tableview列表数据
    if(tag == 1001)
    {
        //  NSLog(@"---------------->>>> %@",responseString);
        
        NSDictionary *dic = [[NSDictionary alloc]init];
        dic = [JsonUtil jsonToDic:responseString];
        
        // NSLog(@"---------------->>>> \n%@",dic);
        
        NSString * strs = dic[@"data"];
        
        NSDictionary *dics =[JsonUtil jsonToDic:strs];
        
        
        NSArray *arryy =(NSArray *)dics;
        
        // NSLog(@"---------00------->>>> %@",arryy);
        
        NSDictionary *dicuu = [arryy objectAtIndex:0];
        
        
        
        
        
        self.Content                    = [dicuu objectForKey:@"Content"];
        self.Image                      = [dicuu objectForKey:@"Image"];
        self.Keywords                   = [dicuu objectForKey:@"Keywords"];
        self.LastChangedTime            = [dicuu objectForKey:@"LastChangedTime"];
        self.Order                      = [dicuu objectForKey:@"Order"];
        self.ReleaseDate                = [dicuu objectForKey:@"ReleaseDate"];
        self.Source                     = [dicuu objectForKey:@"Source"];
        self.Subtitle                   = [dicuu objectForKey:@"Subtitle"];
        self.Summary                    = [dicuu objectForKey:@"Summary"];
        self.Title_massge               = [dicuu objectForKey:@"Title"];
        self.id_massge                  = [[dicuu objectForKey:@"id"] stringValue];
        
        
        //缓存数据(注释因为 数据库创建时未考虑好字段、所以 Title字段改为传图片URL)
        [YZFMDB insertMassge:self.id_massge Data:self.Content Title:self.Image Time:self.ReleaseDate];

        [_bgscrollView removeFromSuperview];
        [self creatViewAndContorller];
      
        
    }
    
    
}

- (void)requestFailed:(NSError *)error andTag:(NSInteger)tag
{
    
    
    
    
}





-(void)creatViewAndContorller
{
    
    //拿到设置字体大小设置
    NSUserDefaults *UserDefaultSize =[NSUserDefaults standardUserDefaults];
    _textFontSize = [UserDefaultSize floatForKey:YZZX_Font_Size];
    
    _bgscrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, Dev_ScreenWidth, Dev_ScreenHeight-64)];
    _bgscrollView.delegate = self;
    //_bgscrollView.contentSize = CGSizeMake(Dev_ScreenWidth*arryDataNav.count, Dev_ScreenHeight-64-30);
    _bgscrollView.bounces = YES;
    //[_bgscrollView setPagingEnabled:YES];            //翻页形式
    //[_bgscrollView setShowsHorizontalScrollIndicator:NO];   //滚动条
    [self.view addSubview:_bgscrollView];


    
    UIImageView *imagebghead = [[UIImageView alloc]initWithFrame:CGRectZero];
    [_bgscrollView addSubview:imagebghead];
    
    [imagebghead sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.hellomommy.cn%@",self.Image]] placeholderImage:[UIImage imageNamed:@"bg.png"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            

            UIImage  *NImage = [self imageCompressForWidth:image targetWidth:Dev_ScreenWidth];
            
            _bgscrollView.contentSize = CGSizeMake(_bgscrollView.contentSize.width, _bgscrollView.contentSize.height+NImage.size.height);
            
            imagebghead.frame = CGRectMake(0, 0,NImage.size.width, NImage.size.height);
            
            bgheadview.frame = CGRectMake(0, imagebghead.bottom, Dev_ScreenWidth, 40+(_textFontSize-13));
            MassgeWebView.frame = CGRectMake(0, bgheadview.bottom, MassgeWebView.frame.size.width, MassgeWebView.frame.size.height);
        });
        
       
        
    }];
    
    
    
    
    
    bgheadview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Dev_ScreenWidth, 40+(_textFontSize-13))];
    [_bgscrollView addSubview:bgheadview];
  //  bgheadview.backgroundColor =[UIColor redColor];
    
    
    
    
    UILabel *labelReleaseDate = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, Dev_ScreenWidth-20, bgheadview.frame.size.height)];
 //labelReleaseDate.backgroundColor =[UIColor greenColor];
    
    labelReleaseDate.font = [UIFont boldSystemFontOfSize:12+(_textFontSize-13)];  //UILabel的字体大小
    labelReleaseDate.numberOfLines = 1;  //必须定义这个属性，否则UILabel不会换行
    labelReleaseDate.textColor = [UIColor grayColor];
    labelReleaseDate.textAlignment = NSTextAlignmentLeft;  //文本对齐方式
    //[labelReleaseDate setBackgroundColor:[UIColor greenColor]];
    labelReleaseDate.text = self.ReleaseDate;
    [bgheadview addSubview:labelReleaseDate];
    
    
    
    
    
    MassgeWebView=[[UIWebView alloc] initWithFrame:CGRectZero];
    MassgeWebView.delegate=self;
    MassgeWebView.frame = CGRectMake(0, bgheadview.bottom, 0, 0);
    

    
    //MassgeWebView.dataDetectorTypes=UIDataDetectorTypeNone;
    MassgeWebView.frame= CGRectMake(0, 0, Dev_ScreenWidth, 0);
    MassgeWebView.scrollView.delegate = self;
    MassgeWebView.scrollView.alwaysBounceVertical = NO;
    MassgeWebView.scrollView.bounces = NO;
    MassgeWebView.scrollView.showsVerticalScrollIndicator = NO;
    [_bgscrollView addSubview:MassgeWebView];
    
    //********************************************字体大小样式设置****************************************
    
    
    
    
    NSString *temstr=@"<style type=\"text/css\">img{max-width:100%;height:auto;} </style>";//只要是img标签都限定大小
    
    NSString *fontString = [NSString stringWithFormat:@"<style type=\"text/css\">*{-webkit-user-select: none;line-height:30px;font-size:%fpx; } </style>", _textFontSize];
    
    NSString *htmlString1 = [NSString stringWithFormat:@"%@%@%@",temstr, fontString, self.Content];//设置大小
    // [_contentWebView loadHTMLString:htmlString1 baseURL:nil]
    
    [MassgeWebView loadHTMLString:htmlString1 baseURL:[NSURL URLWithString:@"http://www.hellomommy.cn/"]];
    
    //     ScrollBackground.contentSize = CGSizeMake(Dev_ScreenWidth, Dev_ScreenHeight-64);
    
    //********************************************字体大小样式设置****************************************
    
    
//    
//    UITapGestureRecognizer *singleTapGestureRecognizer = [[UITapGestureRecognizer alloc]
//                                                          initWithTarget:self action:@selector(handleTapGestureAction:)];
//    singleTapGestureRecognizer.cancelsTouchesInView = NO;
//    singleTapGestureRecognizer.delegate = self;
//    [MassgeWebView addGestureRecognizer:singleTapGestureRecognizer];
//    
    
    
   
}


//
//
//#pragma mark - UIGestureRecognizerDelegate
//
//- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
//{
//    return YES;
//}
//
//- (void)handleTapGestureAction:(UITapGestureRecognizer *)gesture
//{
//    CGPoint curPoint = [gesture locationInView:MassgeWebView];
//    NSString *imgURL = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).src", curPoint.x, curPoint.y];
//    
//    NSString *urlToSave = [MassgeWebView stringByEvaluatingJavaScriptFromString:imgURL];
//    
//    if (!StringIsEmpty(urlToSave))
//    {
//        HXLog(@"%@", urlToSave);
//        
//        HXWebImageView *webImageView = [[HXWebImageView alloc] initWebImageViewWithImageUrl:urlToSave];
//        [webImageView show];
//    }
//}


#pragma mark webview
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
    if(navigationType == UIWebViewNavigationTypeLinkClicked)
    {
        return NO;//禁止点击超链接
    }
    return YES;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    
    NSString *htmlHeight = [MassgeWebView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight"];
    //设置高度
    MassgeWebView.frame =CGRectMake(MassgeWebView.frame.origin.x, MassgeWebView.frame.origin.y, Dev_ScreenWidth,[htmlHeight floatValue]+10);
  
    
    _bgscrollView.contentSize = CGSizeMake(Dev_ScreenWidth,[htmlHeight floatValue]+bgheadview.bottom);

}


//指定宽度按比例缩放
-(UIImage *) imageCompressForWidth:(UIImage *)sourceImage targetWidth:(CGFloat)defineWidth{
    
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = defineWidth;
    CGFloat targetHeight = height / (width / targetWidth);
    CGSize size = CGSizeMake(targetWidth, targetHeight);
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0, 0.0);
    
    if(CGSizeEqualToSize(imageSize, size) == NO){
        
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if(widthFactor > heightFactor){
            scaleFactor = widthFactor;
        }
        else{
            scaleFactor = heightFactor;
        }
        scaledWidth = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        if(widthFactor > heightFactor){
            
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
            
        }else if(widthFactor < heightFactor){
            
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }
    
    UIGraphicsBeginImageContext(size);
    
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    if(newImage == nil){
        
        NSLog(@"scale image fail");
    }
    UIGraphicsEndImageContext();
    return newImage;
}


@end
